package com.example.litemall.admin.api.controller;

import com.example.litemall.admin.api.commons.*;
import com.example.litemall.admin.api.domain.LitemallAdmin;
import com.example.litemall.admin.api.dto.LoginParam;
import com.example.litemall.admin.api.mapper.LitemallAdminMapper;
import com.example.litemall.admin.api.service.LitemallAdminService;
import com.example.litemall.admin.api.service.LitemallPermissionService;
import com.example.litemall.admin.api.service.LitemallRoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.*;


/**
*用户认证授权
*
*@Author kuaiyu
*@Date 2020-07-14 14:42:57
*@see com.example.litemall.admin.api.controller
*/
@RestController
@RequestMapping("/admin/auth")
public class AdminAuthController {
    @Autowired
    private LitemallAdminService adminService;
    @Autowired
    private LitemallRoleService roleService;
    @Autowired
    private LitemallPermissionService permissionService;

    @PostMapping("/login")
    public Object Hello(@Valid @RequestBody LoginParam loginParam, BindingResult bindingResult,
                        HttpServletRequest request){
        if (bindingResult.hasErrors()){
            return ResponseUtil.fail(bindingResult.getErrorCount(),bindingResult.getFieldError().getDefaultMessage());
        }
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(new UsernamePasswordToken(loginParam.getUsername(),loginParam.getPassword()));
        } catch (UnknownAccountException e) {
            return ResponseUtil.fail(ResponseCode.USER_LOGIN_ERROR.code(),"用户名错误");
        }catch (IncorrectCredentialsException e){
            return ResponseUtil.fail(ResponseCode.USER_LOGIN_ERROR.code(),"密码错误");
        }

        currentUser = SecurityUtils.getSubject();
        LitemallAdmin admin = (LitemallAdmin) currentUser.getPrincipal();
        admin.setLastLoginIp(IpUtil.getIpAddr(request));
        admin.setLastLoginTime(LocalDateTime.now());
        adminService.updateAdmin(admin);

//            logHelper.logAuthSucceed("登录");

        // userInfo
        Map<String, Object> adminInfo = new HashMap<String, Object>();
        adminInfo.put("nickName", admin.getUsername());
        adminInfo.put("avatar", admin.getAvatar());

        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("token", currentUser.getSession().getId());
        result.put("adminInfo", adminInfo);
        return ResponseUtil.ok(result);
    }

    @GetMapping("/info")
    public Object info() {
        Subject currentUser = SecurityUtils.getSubject();
        LitemallAdmin admin = (LitemallAdmin) currentUser.getPrincipal();

        Map<String, Object> data = new HashMap<>();
        data.put("name", admin.getUsername());
        data.put("avatar", admin.getAvatar());

        String roleIds = admin.getRoleIds();
        Set<String> roles = roleService.getRolesByIds(roleIds);
        Set<String> permissions = permissionService.getPermissionsByIds(roleIds);
        data.put("roles", roles);
        // NOTE
        // 这里需要转换perms结构，因为对于前端而已API形式的权限更容易理解
        data.put("perms", toApi(permissions));
        return ResponseUtil.ok(data);
    }

    @RequiresAuthentication
    @PostMapping("/logout")
    public Object logout() {
        Subject currentUser = SecurityUtils.getSubject();

        currentUser.logout();
        return ResponseUtil.ok();
    }

    @Autowired
    private ApplicationContext context;
    private HashMap<String, String> systemPermissionsMap = null;

    private Collection<String> toApi(Set<String> permissions) {
        if (systemPermissionsMap == null) {
            systemPermissionsMap = new HashMap<>();
            final String basicPackage = "org.linlinjava.litemall.admin";
            List<Permission> systemPermissions = PermissionUtil.listPermission(context, basicPackage);
            for (Permission permission : systemPermissions) {
                String perm = permission.getRequiresPermissions().value()[0];
                String api = permission.getApi();
                systemPermissionsMap.put(perm, api);
            }
        }

        Collection<String> apis = new HashSet<>();
        for (String perm : permissions) {
            String api = systemPermissionsMap.get(perm);
            apis.add(api);

            if (perm.equals("*")) {
                apis.clear();
                apis.add("*");
                return apis;
                //                return systemPermissionsMap.values();

            }
        }
        return apis;
    }

    @GetMapping("/index")
    public Object pageIndex(){
        return ResponseUtil.ok();
    }
    @GetMapping("/401")
    public Object page401() {
        return ResponseUtil.unlogin();
    }
    @GetMapping("/403")
    public Object page403() {
        return ResponseUtil.unauthz();
    }
}
